<template>
  <div class="user">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="javascript:;">用户管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <div style="margin-top: 15px;">
      <el-input placeholder="请输入内容" @keyup.native.enter="searchUser" class="input-with-select" style=" width:300px" v-model="searchKey">
        <el-button slot="append" icon="el-icon-search" type="success" plain @click='searchUser'></el-button>
      </el-input>
      <el-button type="success" plain @click='addDialogFormVisible=true'>添加用户</el-button>
    </div>
    <template>
      <el-table :data="userList" height="250" border style="width: 100%;margin-top:30px">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="80">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="80">
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeuserstate(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button type="info" icon="el-icon-edit" plain @click="showEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="授权角色" placement="top">
              <el-button type="warning" icon="el-icon-share" plain @click='showRoles(scope.row)'></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" plain @click='deleteUser(scope.row.id)'></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentpage" :page-sizes="pagesizes" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </template>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addUserForm" label-width="100px" ref='addform' status-icon :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addform')">取 消</el-button>
        <el-button type="primary" @click="addUser('addform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form label-width="100px" ref='editform' :model="editform" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserList('editform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配用户角色对话框 -->
    <el-dialog title="授权角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="rolesform" label-width="100px" ref="roles">
        <el-form-item label="用户名:">
          <el-input v-model="rolesform.username" disabled style='width:180px'></el-input>
        </el-form-item>
        <el-form-item label="角色:">
          <!-- 下拉列表 -->
          <el-select v-model="rule_rid" placeholder="请选择" @change='getRid' ref="roleName">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="ruleSubmit('roles')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUserList,
  addUser,
  editUser,
  changeUserState,
  getUserRolesList,
  deleteUserById,
  setUserRole
} from '@/api/index.js'
export default {
  data () {
    var validateEmail = (rule, value, callback) => {
      var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('邮箱输入有误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      roleName: '',
      rule_rid: '',
      searchKey: '',
      rolesList: [],
      rolesform: {
        id: '',
        username: '',
        rid: ''
      },
      grantDialogFormVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userList: [],
      editDialogFormVisible: false,
      editform: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        id: ''
      },
      addDialogFormVisible: false,
      pagesize: 10,
      pagesizes: [10, 20, 30],
      currentpage: 1,
      total: 1,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 删除
    deleteUser (id) {
      this.$confirm(`此操作将永久删除id为${id}的数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUserById(id).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
              if (this.userList.length <= this.pagesize) {
                this.currentpage = this.currentpage - 1
              }
              // 初始化数据
              this.initUserList()
            } else {
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
              // 初始化数据
              this.initUserList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索框
    searchUser () {
      this.initUserList()
    },
    // 下拉列表的change事件
    getRid () {
      console.log(this.rule_rid)
      this.rolesform.rid = this.rule_rid
    },
    // 分配角色确认按钮
    ruleSubmit (roles) {
      setUserRole(this.rolesform).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        this.grantDialogFormVisible = false
        this.resetForm(roles)
      })
    },
    // 角色列表
    showRoles (row) {
      console.log(row)
      this.roleName = row.role_name
      this.rolesform.username = row.username
      this.rolesform.id = row.id
      this.grantDialogFormVisible = true
      getUserRolesList().then(res => {
        this.rolesList = res.data
        console.log(res.data)
      })
    },
    // 修改用户状态
    changeuserstate (row) {
      changeUserState({ uId: row.id, type: row.mg_state }).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'error'
          })
        }
      })
    },
    // 显示编辑内容
    showEdit (row) {
      //   console.log(index, row)
      this.editform.username = row.username
      this.editform.email = row.email
      this.editform.mobile = row.mobile
      this.editform.id = row.id
      this.editDialogFormVisible = true
    },
    // 编辑用户信息
    editUserList (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          editUser(this.editform).then(res => {
            console.log(res)
            if (res.meta.status === 200) {
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
              // 初始化数据
              this.initUserList()
              // 重置表单内容
              this.resetForm(formName)
              this.editDialogFormVisible = false
            } else {
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
              // 重置表单内容
              this.resetForm(formName)
              this.addDialogFormVisible = false
            }
          })
        }
      })
    },
    handleDelete (index, row) {
      console.log(index, row)
    },
    // 每页条数
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.initUserList()
    },
    // 分页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentpage = val
      this.initUserList()
    },
    // 添加用户
    addUser (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addUser(this.addUserForm).then(res => {
            console.log(res)
            if (res.meta.status === 201) {
              // 重置表单内容
              this.resetForm(formName)
              this.$message({
                message: res.meta.msg,
                type: 'success'
              })
              this.addDialogFormVisible = false
              // 初始化数据
              this.initUserList()
            } else {
              this.$message({
                message: res.meta.msg,
                type: 'error'
              })
              // 重置表单内容
              this.resetForm(formName)
              this.addDialogFormVisible = false
            }
          })
        }
      })
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.addDialogFormVisible = false
    },
    // 初始化获取数据
    initUserList () {
      getAllUserList({
        query: this.searchKey,
        pagenum: this.currentpage,
        pagesize: this.pagesize
      }).then(res => {
        console.log(res)
        this.userList = res.data.users
        this.total = res.data.total
      })
    }
  },
  mounted () {
    this.initUserList()
  }
}
</script>

<style lang="scss" scoped>
/* 覆盖element导航菜单的样式 */
.el-breadcrumb {
  background-color: #f5f5f5;
  height: 45px;
  font-size: 15px;
  padding-left: 10px;
  line-height: 45px;
  margin-bottom: 15px;
}
</style>
